package cn.yunhe.test;

import cn.yunhe.entity.Person;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Iterator;
import java.util.List;

public class Demo3 {
    SessionFactory factory = null;
    Session session = null;
    Transaction tr = null;
    @Before
    public void init(){
        Configuration configure = new AnnotationConfiguration().configure();
        //Configuration configure = new Configuration().configure();
        factory = configure.buildSessionFactory();
        session = factory.openSession();
        tr = session.beginTransaction();
    }
    @Test
    public void test1(){//sql语句只会执行一次,进行了缓存
        Person p1 = (Person) session.get(Person.class,2);
        System.out.println("1111"+p1.getUsername());
        session.close();
        session = factory.openSession();
        Person p2 = (Person) session.get(Person.class,2);
        System.out.println("2222"+p2.getUsername());
        session.close();
    }
    @Test
    public void test2(){
        Query query =session.createQuery("from Person");
        query.setCacheable(true);
        List<Person> list  = query.list();
        for (Person person : list) {
            System.out.println(person.getUsername());
        }
        session.close();
        System.out.println("================");

        session = factory.openSession();
        Query query2 = session.createQuery("from Person");
        query2.setCacheable(true);
        List<Person> list2 = query2.list();
        for (Person person : list2) {
            System.out.println(person.getUsername());
        }
        session.close();
    }
    /*@After
    public void destory(){
        tr.commit();
        session.close();
    }*/
}
